package com.jfplugin.xsql.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.jfplugin.xsql.exception.SqlMapPathException;
import com.jfplugin.xsql.statement.SqlStatement;

/**
 * 
 * @author farmer
 *
 */
public class SqlConfigParser {

	private SqlStatementMapping statementMapping = new SqlStatementMapping();
	
	private NodeParser nodeParser = new NodeParser();
	
	public void parser(InputStream in){
		Document doc = nodeParser.parser(in);
		Node sqlconfignode = doc.getElementsByTagName("sqlconfig").item(0);
		NodeList children = sqlconfignode.getChildNodes();
		for (int i = 0; i < children.getLength(); i++) {
			Node node = children.item(i);
			
			if("statements".equals(node.getNodeName().toLowerCase())){
				NodeList statements = node.getChildNodes();
				for (int j = 0; j < statements.getLength(); j++) {
					Node statement = statements.item(j);
					if("statement".equals(statement.getNodeName().toLowerCase())){
						String tag = nodeParser.attr(statement, "tag");
						String clazz = nodeParser.attr(statement, "class");
						StatementBuilder.register(tag, clazz);
					}
					
				}
				
			}
			
			
			
			if("sqlmap".equals(node.getNodeName().toLowerCase())){
				String path = node.getAttributes().getNamedItem("path").getNodeValue();
				InputStream sqlmapin = null;
				try {
					if(path.startsWith("file:")){
						sqlmapin = new FileInputStream(new File(path.replace("file:", "")));
					}
					else{
						sqlmapin = getClass().getClassLoader().getResourceAsStream(path.replace("classpath:", ""));
					}
					new SqlMapParser().parser(sqlmapin , statementMapping);
				} catch (Exception e) {
					throw new SqlMapPathException("sqlmap 的 path:"+path+"，异常",e);
				}finally{
					if(sqlmapin != null){
						try { sqlmapin.close(); } catch (IOException e) { e.printStackTrace(); }
					}
					
				}
			}
			
		}
	}
	
	/**
	 * 
	 * @param sqlId
	 * 	SQLID
	 * @return
	 * 	SqlStatement
	 */
	public SqlStatement get(String sqlId){
		return statementMapping.get(sqlId);
	}
	/*
	public SqlStatementMapping getStatementMapping() {
		return statementMapping;
	}

	public void setStatementMapping(SqlStatementMapping statementMapping) {
		this.statementMapping = statementMapping;
	}
	*/
	
}